
const { show, msg } = require("./alert");
let { adPosition, shopData, weatherList, foodList, customerList, time, player, achieveProcess, times } = require("../shop/gameData");
const { player1, adPosition1, shopData1, time1 } = require('./gameInitData');
const { ADS } = require("../ads/ADS");
const { GLRandom } = require("../util/random");
const EventServices = require("../util/EventServices");
const { videoAds } = require("../ads/video");
 // 等级                        1   2   3   4   5   
                    // 1级顾客 80   10  10  0   0
                    // 2级顾客 30   50  10  5   5   
                    // 3级顾客 10   20  50  15  5
                    // 4级顾客 10   10  20  50  10
                    // 5级顾客 5    10  10  10  65
let customerFoodList = [
    [
        [1,0.8],[2,0.1], [3,0.1]
    ],
    [
        [1,0.3],[2,0.5], [3,0.2]
    ],
    [
        [1,0.2],[2,0.3], [3,0.5]
    ],

]
let random = new GLRandom(1, 4);
function randomCustomerFood(level){
    
        // 调整概率
    random.percentage = new Map(customerFoodList[level-1]);
    // 生成值区间
    random.range();
    
        // 生成概率随机数
    return random.create();
}
cc.Class({
    extends: cc.Component,
    properties: {
        day:cc.Label,
        hour:cc.Label,
        min:cc.Label,
        speed:0.5,
        shopList:cc.Node,
        shopBanner:cc.RichText
    },
    onLoad () {
        cc.log('timer初始化游戏数据了')
        // this.init();
        this.randomWeather();//随机天气
        this.randomMenuList();//生成菜单
        this.initShopStock();//生成库存
        this.schedule(this.updateTime,this.speed);//计时开始
        
        
    },
    init() {
        let playperson = cc.sys.localStorage.getItem('player');
        cc.log(cc.sys.localStorage.getItem('player'))
        if(playperson) {
            //读取进度
            player = JSON.parse(playperson);
            console.log(player);
            adPosition = JSON.parse(cc.sys.localStorage.getItem('adPosition'));
            time = JSON.parse(cc.sys.localStorage.getItem('time'));
        }else {
            // shopData = JSON.parse(JSON.stringify(shopData1));
            player = JSON.parse(JSON.stringify(player1));
            time = JSON.parse(JSON.stringify(time1));
            adPosition = JSON.parse(JSON.stringify(adPosition1));
        }
    },
    update(){
        this.randerTime();
    },
    randerTime(){
        this.day.string = time.day;
        this.hour.string = time.hour;
        if(time.hour<10){
            this.hour.string = "0"+time.hour;
        }else{
            this.hour.string = time.hour;
        }
        if(time.min<10){
            this.min.string = "0"+time.min;
        }else{
        this.min.string = time.min;
        }
    },
    calMoney() {
        // 店铺财富
        let money = 0;
        money += player.money;
        shopData.shopList.forEach(val => {
            money += val.money;
            money -= val.debt.money + val.debt.interest * val.debt.month;
        })
        return money;
    },
    //更新时间
    updateTime () {
        time.min += 1;
        
        this.refreshOrders();
            if(time.min%10 == 0){
                this.calTransport();//计算配送时间
                this.calshopCustomer(parseInt(time.hour));//计算顾客
            }
            // if(time.min%20 == 0){
                
            // }
            if(time.min>=60){
                time.min = 0;
                time.hour += 1;
                // this.updateStockDelivery();//更新配送情况
                if(time.hour>=24){
                   
                    if(Math.random() >= 0.3 && times.count > 0) {
                        show('未来投资','公司需要投资吗？,我钱太多了', res => {
                            if(res){
                                videoAds.showAd(wd => {
                                    if(wd) {
                                        msg('获取融资2w元');
                                        player.money += 20000;
                                        achieveProcess.ad ++;
                                    }
                                });
                            }
                        })
                    }
                    this.scheduleOnce(() => {
                        msg('店铺打烊了');
                    },5)
                    this.randomWeather();//随机天气
                    //更新店铺的状态，收入，顾客等
                    this.clearShopDay();
                    time.hour = 0;
                    time.day += 1;
                    cc.sys.localStorage.setItem('shopList', JSON.stringify(shopData));
                    cc.sys.localStorage.setItem('player', JSON.stringify(player));
                    cc.sys.localStorage.setItem('time', JSON.stringify(time));
                    cc.sys.localStorage.setItem('times', JSON.stringify(times));
                    cc.sys.localStorage.setItem('adPosition', JSON.stringify(adPosition));
                    cc.sys.localStorage.setItem('achieveProcess', JSON.stringify(achieveProcess));
                    if(time.day%30 == 0){
                        // let month = time.day/30;
                        // if(parseInt(window.mode) <= month) {
                        //     let wealth = this.calMoney();
                        //     this.unschedule(this.updateTime);
                        //     show('未来科技','游戏结束了,您的累计财富为'+wealth);
                        //     //保存数据
                        //     let arr = JSON.parse(cc.sys.localStorage.getItem('rank'));
                        //     if(!arr) {
                        //         arr = [];
                        //     }
                        //     arr.push({name: cc.sys.localStorage.getItem('shopName'), wealth});
                        //     arr = arr.sort((a, b) => b.wealth - a.wealth);
                        //     cc.sys.localStorage.setItem('rank', JSON.stringify(arr));
                        // }
                        //收租
                        this.rentMoney();
                        // this.payForDebt();
                        // if(time.day >= mode) {
                        //     show('未来科技','游戏结束');
                        //     cc.director.loadScene('start');
                        // }
                    }
                }
            }
    },
    calTransport() {
        shopData.shopList.forEach(val => {
            if(val.status == 1 && val.transportList) {
                val.transportList.forEach((item, i) => {
                    item.transport -= 10;
                    if(item.transport <= 0) {
                        //配送完成
                        let food = val.transportList.splice(i, 1);//删除配送的
                        //更新库存
                        let foodIdx = val.foodList.findIndex(foodItem => foodItem.id == food[0].id);
                        val.foodList[foodIdx].stock += food[0].stock;
                        val.saleList.push(`您的${food[0].name}已送达`);
                        EventServices.publish('transportOver', foodIdx, val.foodList[foodIdx].stock);
                    }
                })
            }
        })
    },
    //设置倍数
    setSpeed(target,speed){ 
        let tmpSpeed = this.speed/speed;
        this.unschedule(this.updateTime);
        this.schedule(this.updateTime,tmpSpeed);
    },
    rentMoney(){
        shopData.shopList.forEach(val=>{
           if(val.status == 1){
                val.money -= val.debt.interest;
                val.debt.month --;
                if(val.debt.month <= 0){
                    val.money -= val.debt.money;
                    // val.debt.money = 0;
                }
           }
         })
        //  msg('该还钱了噢');

    },
    refreshOrders() {
        shopData.shopList.forEach(val => {
            if(val.status == 1 && val.makeList){
                //遍历店员
            //查看做好的订单
            //所有人等待时间增加
                val.makeList.forEach((order, index) => {
                    order.leftTime --;
                    order.waitTime ++;
                    if(order.leftTime <= 0){
                        let arr = val.makeList.splice(index, 1);
                        if(arr[0].waitTime >= arr[0].maxWait) {
                            //超出等待时间
                            if(Math.random() >= 0.3 ){
                                val.saleList.push(`${arr[0].name},等太久了，差评+1,<color=#CD7F32>+＄${(arr[0].cost*(val.leftStock/100)).toFixed(1)}</color>`);
                                val.famous -= arr[0].level;
                                if(val.famous <= 0){
                                    val.famous = 0;
                                }
                            }else {
                                val.saleList.push(`${arr[0].name},**玩意，做个奶茶这么久,<color=#CD7F32>+＄${(arr[0].cost*(val.leftStock/100)).toFixed(1)}</color>`);
                            }
                            
                        }
                        if(Math.random() >= 0.6) {
                            val.saleList.push(`${arr[0].name},还不错，好评+1,<color=#CD7F32>+＄${(arr[0].cost*(val.leftStock/100)).toFixed(1)}</color>`);
                            val.famous += arr[0].level;
                        }else {
                            val.saleList.push(`${arr[0].name},<color=#CD7F32>+＄${(arr[0].cost*(val.leftStock/100)).toFixed(1)}</color>`);
                        }
                        if(val.famous>=10000) {
                            val.famous = 10000;
                        }
                        if(val.saleList.length > 12 ){
                            val.saleList.shift();
                        }
                        val.customer++;
                        val.freeWork ++;
                        //直接查看排队人数
                        if(val.customerList.length > 0) {
                            val.freeWork --;
                            val.makeList.push(val.customerList.shift());
                        }
                    }
                })
                val.customerList.forEach(tmp => {
                    tmp.waitTime++;
                })
                while(val.freeWork > 0 &&val.customerList.length > 0) {
                    val.freeWork --;
                    val.makeList.push(val.customerList.shift());
                }
            }
            
        })
    },
    //每个月计算还款
    payForDebt() {
        shopData.shopList.forEach(val => {
            if(val.status == 1) {
                val.money -= val.rent/30;
            }
        })
    },
    //解锁5倍数
    unlockFiveSpeed(){
        cc.log(adPosition)
        if(adPosition.speed){
            //开通的话直接加速
            this.setSpeed(null,5);
        }else{
            videoAds.showAd((res)=>{
                if(res){
                    this.setSpeed(null,5);
                    adPosition.speed = true;
                    msg('今天广告剩余'+ times.count);
                }
            })
        }
    },
    //随机天气
    randomWeather(){
        shopData.shopList.forEach(val=>{
           val.weather = weatherList[Math.round(Math.random()*(weatherList.length-1))];
        })
    },
    //计算店铺收入
    calShopIncome () {

    },
    //每天清空店铺数据
    clearShopDay () {
        
        shopData.shopList.forEach(val=>{
            if(val.status == 1){
                val.income = 0;
                val.customer = 0;
                // if(val.foodList) {
                //     val.foodList.forEach(food => food.monthSales = 0);
                // }
                // val.foodList.sort((a, b) => b.sales-a.sales);
                //计算每天租金和人工费用
                val.money -= parseInt(val.rent/30);
            }
        });
        this.updateShopList();
    },
    //计算顾客
    calshopCustomer (time) {
        //计算公式
        // 进入的顾客等于 基础顾客*天气影响+名声
        let timeEffect = 1;
        if(time>=0&&time<=10){
            timeEffect = 0;
        }else if(time>10&&time<=13){
            timeEffect = 0.5;
        }else if(time>13&&time<=18){
            timeEffect = 1.5;
        }else{
            // time>18&&time<=24;
            timeEffect = 22;
        }
        let bannerText = '';

        shopData.shopList.forEach((val,shopIndex)=>{
            if(val.status == 1 && val.foodList){
                if(val.customerList.length >= 200){
                    bannerText = '人太多了，多雇点人手吧！';
                }else {

                let customerNum = Math.ceil(timeEffect*(val.famous/2000)*(((val.loaction * 2)*(Math.random()*(10-val.weather.effect))))*(val.foodList.length/val.menuList.length));
                if(customerNum < 0) {
                    customerNum = 0;
                }
                val.customer += customerNum;
                //每个顾客消费
                //随机生成顾客镜像
                for(let i = 0; i<customerNum;i++){
                    if(val.customerList.length>=200) {
                        return ;
                    }
                    let customer = customerList[val.level - 1]; //Math.round(Math.random()*(customerList.length-1))
                    //随机消费下
                    //规则: 根据顾客等级消费，如果没有对应的产品，也会扣除相应的金币，顾客有可能立刻离开店铺
                    // 高级顾客会想消费对应的高级餐饮，如果没有，顾客会离开，并降低名声，数值为顾客等级。
                    //先生成顾客的菜单 
                    // 等级     1   2   3   4   5   
                    // 1级顾客 80   10  10  0   0
                    // 2级顾客 30   50  10  5   5   
                    // 3级顾客 10   20  50  15  5
                    // 4级顾客 10   10  20  50  10
                    // 5级顾客 5    10  10  10  65
                    // let foodLevel = randomCustomerFood(customer.level);
                    // 在食品中随机生成
                    // let myList = foodList[foodLevel-1].list;
                    // let buyFood = myList[Math.round(Math.random()*(myList.length-1))];
                    let buyFood = val.foodList[Math.round(Math.random()*(val.foodList.length-1))];
                    // let buyFood = myList[0];
                    //买了什么 
                    // 能否做出来了
                    //先遍历查看食材
                    //先看菜单有没有
                    let tmpMenu = val.foodList.find(menu=>buyFood.id == menu.id);
                    let menuIndex = val.foodList.findIndex(val =>val.id == buyFood.id);
                    if(tmpMenu.stock == 0 ||tmpMenu.state == 0){   
                        //降低知名度
                        val.famous -= 1;
                        if(val.famous <= 0){
                            val.famous = 0;
                        }
                        bannerText =  tmpMenu.name + '都没有，做**吧**';
                        val.saleList.push(bannerText);
                        if(val.saleList.length >12 ){
                            val.saleList.shift();
                        }
                    }else{
                            bannerText = '您有新的订单，请注意查收';
                            tmpMenu.stock --;
                            achieveProcess.sale ++;//成就的
                            if(window.shopId && window.shopId == val.id) {
                                EventServices.publish('shopUpdate', shopIndex, menuIndex);//更新库存
                            }
                            //进行客户和电员更新
                            let order = {leftTime: 5, level: customer.level, cost:buyFood.price, name: customer.name +"下单了"+ buyFood.name, waitTime: 0, maxWait: (4 - customer.level) * 5+2};
                            //将顾客信息存起来
                            val.customerList.push(order);
                        
                            tmpMenu.sales ++;
                            tmpMenu.monthSales++;
                            val.income += buyFood.price;
                            val.money += buyFood.price;
                           
                    }
                }
                
                    // {id:4,name:"超级顾客",money:1000,level:4},
                    // 
                }
            }
        })
        if(window.shopId) {
            this.shopBanner.string = bannerText;
       }else {
           this.shopBanner.string = "暂无营业信息";
       }
        this.updateShopList();
    },
    //更新店铺状态
    updateShopList () {
        let index = 0;
        shopData.shopList.forEach(val=>{
            if(val.status == 1){
                let tmp =  this.shopList.children[index];
                if(tmp){
                    tmp.getChildByName("workers").getComponent(cc.Label).string = `员工：${val.workers}`
                    tmp.getChildByName("income").getComponent(cc.Label).string = `收入：${val.income}`
                    tmp.getChildByName("status").getComponent(cc.Label).string = `状态：营业中`
                    tmp.getChildByName("money").getComponent(cc.Label).string = `账户：${val.money}`
                    tmp.getChildByName("customer").getComponent(cc.Label).string = `顾客：${val.customer}`
                }
                index++;
            }
            
        })
    },
    //初始化店铺库存
    initShopStock () {
        if(!cc.sys.localStorage.getItem('shopList')){
            shopData.shopList.forEach(val=>{
                val.saleList = []
            });
        }
    },
    //更新仓库配送时间
    updateStockDelivery(){
        shopData.shopList.forEach(val=>{
            val.stock.forEach(item=>{
                item.transport-=1;
                if(item.transport<=0)item.transport=0;
            })
        })
    },
    //初始化店铺的菜单
    randomMenuList () {
        foodList.forEach(val => {
            val.list.forEach(food => {
                food.transport = val.level * 20;
                food.sales = 0;
                food.monthSales = 0;
                food.state = 0;
                food.unlockFamous = food.level * 50;
                food.unlockMoney = 1000 * food.level;
            })
        })
        if(cc.sys.localStorage.getItem('player')){
            return ;
        }
        shopData.shopList.forEach(val=>{
                //初始化店铺的贷款
                // {
                    // debt:1200, month: 3, interest: 123, rate:0.24,
                // }
                val.debt = {
                    money:0, month: 0, interest: 0 ,rate: 0.24
                }
                //初始化店员和顾客信息
                val.saleList = []
                val.freeWork = 3;
                //顾客
                val.customerList = [];
                val.makeList = [];
                //配送
                val.transportList = [];
                //初始化店铺菜单 每个等级的生成7个
                
                if(val.status == 1) {
                    val.menuList = JSON.parse(JSON.stringify(foodList[val.level - 1].list));
                }
               
                val.foodList = []
            })
       
        
    }
});
